from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page, get_first_error
from BloodSpiderAPI.apis.dailianwanzi.request import dlwz
from BloodSpiderAPI.apis.order import utils as order_utils
from django import forms
from django.core.validators import RegexValidator, MinLengthValidator, MaxLengthValidator
from BloodSpiderAPI import models
from django.db.models import Q
import time
from django.forms.models import model_to_dict
import decimal


# 订单表单验证
class OrderForm(forms.ModelForm):
    class Meta:
        model = models.OrderList
        fields = []


# 子订单表单验证
class SubOrderForm(forms.ModelForm):
    sub_order_name = forms.CharField(
        max_length=255,
        required=True,
        error_messages={
            'required': '子订单名称不能为空',
            'max_length': '子订单名称不能超过255个字符'
        }
    )
    
    sub_order_no = forms.CharField(
        max_length=255,
        required=True,
        error_messages={
            'required': '子订单编号不能为空',
            'max_length': '子订单编号不能超过255个字符'
        }
    )
    
    price = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        required=False,
        min_value=0,
        error_messages={
            'min_value': '价格不能为负数',
            'max_digits': '价格数值过大',
            'decimal_places': '价格小数位数过多'
        }
    )
    
    margin = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        required=False,
        min_value=0,
        error_messages={
            'min_value': '保证金不能为负数',
            'max_digits': '保证金额值过大',
            'decimal_places': '保证金小数位数过多'
        }
    )
    
    class Meta:
        model = models.SubOrder
        fields = ["sub_order_name", "sub_order_no", "price", "margin"]


# 创建订单API
def create_order(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    try:
        order = models.OrderList.objects.create()
        response = order_utils.utils_model_to_dict(order)
        return response_dict(data=response, message="订单创建成功")
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)


# 删除订单API
def delete_order(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    order_id = request.POST.get('order_id')
    if not order_id:
        return response_dict(message="缺少订单ID参数", code=1)

    try:
        order = models.OrderList.objects.get(order_id=order_id)
        order.delete()
        return response_dict(message="订单删除成功")
    except models.OrderList.DoesNotExist:
        return response_dict(message="订单不存在", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)


# 获取订单详情API
def get_order(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    order_id = request.GET.get('order_id')
    if not order_id:
        return response_dict(message="缺少订单ID参数", code=1)

    try:
        # 获取订单详情（包含子订单）
        order_detail = order_utils.get_order_detail(order_id)
        if not order_detail:
            return response_dict(message="订单不存在", code=1)
        return response_dict(data=order_detail, message="获取成功")
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 创建子订单API
def create_sub_order(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    form = SubOrderForm(request.POST)
    if not form.is_valid():
        return response_dict(data=get_first_error(form), code=1, message="参数错误")

    order_id = request.POST.get('order_id')
    if not order_id:
        return response_dict(message="缺少订单ID参数", code=1)

    try:
        # 检查订单是否存在
        order = models.OrderList.objects.get(order_id=order_id)
        
        # 创建子订单
        sub_order = form.save(commit=False)
        sub_order.order_id = order
        sub_order.save()
        
        response = order_utils.utils_model_to_dict(sub_order)
        return response_dict(data=response, message="子订单创建成功")
    except models.OrderList.DoesNotExist:
        return response_dict(message="订单不存在", code=1)
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)


# 删除子订单API
def delete_sub_order(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    sub_order_id = request.POST.get('sub_order_id')
    if not sub_order_id:
        return response_dict(message="缺少子订单ID参数", code=1)

    try:
        sub_order = models.SubOrder.objects.get(sub_order_id=sub_order_id)
        sub_order.delete()
        return response_dict(message="子订单删除成功")
    except models.SubOrder.DoesNotExist:
        return response_dict(message="子订单不存在", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)


# 更新子订单API
def update_sub_order(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    sub_order_id = request.POST.get('sub_order_id')
    if not sub_order_id:
        return response_dict(message="缺少子订单ID参数", code=1)

    try:
        sub_order = models.SubOrder.objects.get(sub_order_id=sub_order_id)
        update_data = {}

        # 检查并添加可更新字段
        if 'sub_order_name' in request.POST and request.POST['sub_order_name']:
            update_data['sub_order_name'] = request.POST['sub_order_name']
        if 'sub_order_no' in request.POST and request.POST['sub_order_no']:
            update_data['sub_order_no'] = request.POST['sub_order_no']
        if 'price' in request.POST and request.POST['price']:
            try:
                update_data['price'] = decimal.Decimal(request.POST['price'])
            except decimal.InvalidOperation:
                return response_dict(message="价格格式无效", code=1)
        if 'margin' in request.POST and request.POST['margin']:
            try:
                update_data['margin'] = decimal.Decimal(request.POST['margin'])
            except decimal.InvalidOperation:
                return response_dict(message="保证金格式无效", code=1)

        # 如果没有任何可更新字段
        if not update_data:
            return response_dict(message="没有提供可更新字段", code=1)

        # 更新子订单
        models.SubOrder.objects.filter(sub_order_id=sub_order_id).update(**update_data)
        
        # 获取更新后的子订单
        updated_sub_order = models.SubOrder.objects.get(sub_order_id=sub_order_id)
        response = order_utils.utils_model_to_dict(updated_sub_order)
        
        return response_dict(data=response, message="子订单更新成功")
    except models.SubOrder.DoesNotExist:
        return response_dict(message="子订单不存在", code=1)
    except Exception as e:
        return response_dict(message=f"更新失败: {str(e)}", code=1)


# 获取子订单详情API
def get_sub_order(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    sub_order_id = request.GET.get('sub_order_id')
    if not sub_order_id:
        return response_dict(message="缺少子订单ID参数", code=1)

    try:
        sub_order = models.SubOrder.objects.get(sub_order_id=sub_order_id)
        response = order_utils.utils_model_to_dict(sub_order)
        return response_dict(data=response, message="获取成功")
    except models.SubOrder.DoesNotExist:
        return response_dict(message="子订单不存在", code=1)
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)




# 获取订单列表API，支持分页
def get_order_list(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    try:
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        
        # 获取所有订单
        all_orders = [order_utils.get_order_detail(item.order_id) for item in models.OrderList.objects.all()]
        
        # 应用分页
        # paginated_result = get_page(all_orders,page_size, page)
        
        # # 确保返回格式一致
        # if not paginated_result:
        #     paginated_result = {'data': [], 'total': 0, 'page': page, 'page_size': page_size}
        
        return response_dict(data=all_orders, message="获取成功")
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 根据子订单编号查询关联订单API
def get_order_by_sub_order_no(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    sub_order_no = request.GET.get('sub_order_no')
    if not sub_order_no:
        return response_dict(message="缺少子订单编号参数", code=1)

    try:
        # 根据子订单编号查询子订单
        sub_orders = models.SubOrder.objects.filter(sub_order_no=sub_order_no)
        
        if not sub_orders.exists():
            return response_dict(message="未找到匹配的子订单", code=1)
        
        # 获取所有关联的订单
        order_ids = set()
        order_details = []
        
        for sub_order in sub_orders:
            order_id = sub_order.order_id.order_id
            if order_id not in order_ids:
                order_ids.add(order_id)
                # 获取订单详情（包含所有子订单）
                order_detail = order_utils.get_order_detail(order_id)
                if order_detail:
                    order_details.append(order_detail)
        
        return response_dict(data=order_details, message="获取成功")
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


